<?php

namespace App\Admin\Actions\NewworkOrder;


use App\Models\AdminUserModel;
use App\Models\yb\GoodsModel;
use App\Models\yb\GoodsOrderDetailModel;
use App\Models\yb\NetworkCreditRecordModel;
use App\Models\yb\NetworkGoodsModel;
use App\Models\yb\UserAddressModel;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use EasyWeChat\Factory;

class OrderService extends RowAction
{
    public $name = '送达';

    /**
     * @param Model $model
     * @return string
     */
    public function handle(Model $model)
    {

        $config = [
            'app_id' => env('WECHAT_CLIENT_APP_ID'),  // 这里需要自行修改
            'secret' => env('WECHAT_CLIENT_APP_SECRET'),  // 这里需要自行修改
            'response_type' => 'array',
            'log' => [
                'level' => 'debug',
                'file' => 'wechat.log',
            ],
        ];
        $app = Factory::miniProgram($config);

        $user_address = UserAddressModel::where(['id'=>$model->address_id])->first();

        $goods_order_detail = GoodsOrderDetailModel::where(['order_sn'=>$model->order_sn])->get();
        $goods_data_str = "";
        foreach($goods_order_detail as $key=>$val){
            $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->first();
            $goods_data_str = $goods_data_str.",".mb_substr($goods_data['goods_title'],6);
        }
        $goods_data_str = mb_substr($goods_data_str,1);

        $staff_data = AdminUserModel::where(['id'=>$model->staff_id])->first();

        $data = [
            'template_id' => '_vi9FPk9T890fkO1idakNTlzYlmBFiqAPogPCoi0HvU', // 所需下发的订阅模板id
            'touser' => $model->openid,     // 接收者（用户）的 openid
            'page' => '/pages/index/order',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'thing1' => array('value' => $user_address['address']),
                'time2' =>array('value'=> date('Y-m-d H:i:s',time())),
                'thing3' => array('value' => $goods_data_str),
                'thing4' => array('value' => $staff_data['name']),
                'phone_number5' => array('value' => $staff_data['mobile']),
            ],
        ];
        $app->subscribe_message->send($data);

        if($model->status != 2){
            return $this->response()->error('状态错误')->refresh();
        }

         $model->status = 3;
         $model->service_date=date('Y-m-d H:i:s',time());
         $model->save();

        $network_credit_record_data =[];

        foreach($goods_order_detail as $key=>$val){

            NetworkGoodsModel::where(['network_id'=>$model->network_id,'goods_id'=>$val['goods_id']])->increment('return_credit',$val['number']);
            $network_credit_record_data[] = [
                'network_id' => $model->network_id,
                'goods_id' => $val['goods_id'],
                'number' => $val['number'],
                'amount' => $val['amount']* $val['number'],
                'remark' => '售卖商品',
                'status' => 1,
                'relation_data' => $model->order_sn,
                'type' => 2,
                'created_at' => date('Y-m-d H:i:s',time())
            ];
            $goods_data = GoodsModel::where(['id'=>$val['goods_id']])->select(['distribution_fee'])->first();
            AdminUserModel::where(['id'=>$model->network_id])->increment('distribution_price',$goods_data['distribution_fee']);
            $network_credit_record_data[] = [
                'network_id' => $model->network_id,
                'goods_id' => $val['goods_id'],
                'number' => $val['number'],
                'amount' =>$goods_data['distribution_fee'],
                'remark' => '售卖商品',
                'status' => 1,
                'relation_data' => $model->order_sn,
                'type' => 4,
                'created_at' => date('Y-m-d H:i:s',time())
            ];
        }

        NetworkCreditRecordModel::insert($network_credit_record_data);

        return $this->response()->success('操作成功')->refresh();

    }

    /**
     * @param $star
     * @return string
     */
    public function display($id)
    {
        return '<button type="button" style="background-color:#605ca8;color: white;" class="btn btn-xs btn-flat" >送达</button>';
    }

    public function dialog()
    {
        $this->confirm('您确定该订单已送达了吗？');
    }

}
